Ext.ns('AIR2.Submission.Responses')
/***************
 * Submission Responses Panel
 */
AIR2.Submission.Responses = function() {
    var myAnnots = {};

    /* function for ajax showing/hiding annotations on individual responses */
    AIR2.Submission.Responses.showAnnotation = function(el, id) {
        if (myAnnots[id]) {
            // already open --> close and destroy
            Ext.fly(el.nextSibling).fadeOut({concurrent: true}).slideOut('t', {
                callback: function() {
                    myAnnots[id].destroy();
                    delete myAnnots[id];
                }
            });
        }
        else {
            Ext.fly(el.nextSibling).setStyle('display', 'none');

            // not open --> create and open
            var dv = new AIR2.UI.JsonDataView({
                url: AIR2.HOMEURL + '/response/' + id + '/annotations.json',
                renderTo: el.nextSibling,
                itemSelector: '.annotation-mini',
                tpl: new Ext.XTemplate(
                    '<tpl for="."><table class="annotation-mini"><tr>' +
                      '<tpl if="this.exists(values)">' +
                        '<td class="who">' +
                          '<div class="info air2-corners" style="min-height:30px">' +
                            '<strong>{[AIR2.Format.userName(values.CreUser, true)]}</strong>' +
                            '{[this.sysuser(values.CreUser)]}' +
                            '<p>{[AIR2.Format.userOrgTitle(values.CreUser.UserOrg[0],20)]}</p>' +
                            '<div style="padding-top:5px">' +
                              '{[AIR2.Format.userOrgShort(values.CreUser.UserOrg[0], true)]}' +
                            '</div>' +
                          '</div>' +
                        '</td>' +
                        '<td class="text">' +
                          '<p>{sran_value}</p>' +
                          '<div class="meta">' +
                            '<span>{[this.postdate(values)]}</span>' +
                            '<tpl if="this.showedit(values)">' +
                              '<a class="annot-edit">Edit</a>' +
                            '</tpl>' +
                          '</div>' +
                        '</td>' +
                      '</tpl>' + //end this.exists()
                    '</tr></table></tpl>',
                    {
                        compiled: true,
                        disableFormats: true,
                        exists: function(v) {return (v.CreUser) ? true : false},
                        sysuser: function(u) {
                            return (u.user_type == 'S') ? '<p>System User</p>' : '';
                        },
                        postdate: function(v) {
                            if (v.sran_upd_dtim > v.sran_cre_dtim)
                                return 'Updated ' + AIR2.Format.date(v.sran_upd_dtim);
                            else
                                return 'Posted ' + AIR2.Format.date(v.sran_cre_dtim);
                        },
                        showedit: function(v) {
                            return (AIR2.USERINFO.uuid == v.CreUser.user_uuid);
                        }
                    }
                ),
                refresh: function() {
                    // don't do the empty-text thing... just render the tpl
                    this.clearSelections(false, true);
                    var el = this.getTemplateTarget(), rs = this.store.getRange();
                    el.update('');
                    this.tpl.overwrite(el, this.collectData(rs, 0));
                    this.all.fill(Ext.query(this.itemSelector, el.dom));
                    this.updateIndexes(0);
                },
                listeners: {
                    load: function() {Ext.fly(el.nextSibling).fadeIn()},
                    render: function() {
                        // click-listener for editing annotations
                        this.el.on('click', function(e) {
                            if (e.getTarget('.annot-edit')) {
                                var n = e.getTarget('.annotation-mini');
                                var r = this.getRecord(e.getTarget('.annotation-mini'));
                                var p = new Ext.Container({
                                    renderTo: document.createElement('td'),
                                    cls: 'text',
                                    items: [{
                                        xtype: 'textarea',
                                        grow: true,
                                        growMin: 40,
                                        width: '100%'
                                    },{
                                        xtype: 'air2button',
                                        text: 'Save',
                                        air2type: 'SAVE',
                                        air2size: 'MEDIUM',
                                        handler: function(btn) {
                                            r.set('sran_value', btn.previousSibling().getValue());
                                            r.store.save();
                                            p.destroy();
                                        }
                                    },{
                                        xtype: 'air2button',
                                        text: 'Cancel',
                                        air2type: 'CANCEL',
                                        air2size: 'MEDIUM',
                                        handler: function() {
                                            this.refreshNode(this.indexOf(n));
                                            p.destroy();
                                        },
                                        scope: this
                                    }]
                                });

                                // render (and replace existing)
                                p.el.replace(e.getTarget('.text'));
                                p.get(0).setValue(r.data.sran_value);
                                e.stopEvent();
                            }
                        }, this);
                    }
                }
            });
            myAnnots[id] = dv;

            var c = new Ext.Container({
                renderTo: el.nextSibling,
                autoEl: 'table',
                cls: 'annotation-mini',
                items: {
                    xtype: 'container',
                    autoEl: 'tr',
                    items: [{
                        xtype: 'box',
                        autoEl: 'td',
                        cls: 'who',
                        html: '<div class="info air2-corners"><strong>Add an Annotation</strong></div>'
                    },{
                        xtype: 'container',
                        autoEl: 'td',
                        cls: 'text',
                        items: [{
                            xtype: 'textarea',
                            grow: true,
                            height: 40,
                            width: '100%'
                        },{
                            xtype: 'air2button',
                            air2size: 'MEDIUM',
                            text: 'Add',
                            handler: function() {
                                var t = this.previousSibling();
                                if (t.getValue().length < 1) return;
                                var n = new dv.store.recordType;
                                n.set('sran_value', t.getValue());
                                dv.store.add(n);
                                t.reset();
                                dv.store.on('save', function() {
                                    Ext.fly(el).update(dv.store.getCount());
                                }, this, {single:true});
                                dv.store.save();
                            }
                        }]
                    }]
                }
            });
            dv.on('destroy', function(){c.destroy()}, this, {single:true});
        }
    }; //end showAnnotation function


    // get submission meta
    var src = AIR2.Format.sourceFullName(AIR2.Submission.SRCDATA.radix, true);
    var subm = AIR2.Submission.SUBMDATA.radix;
    var submDate = AIR2.Format.date(subm.srs_date);
    var creator = AIR2.Format.userName(subm.Inquiry.CreUser, true);
    var org = AIR2.Format.userOrgShort(subm.Inquiry.CreUser.UserOrg[0], true);
    var dtim = AIR2.Format.date(subm.Inquiry.inq_cre_dtim);
    var shared = (subm.Inquiry.inq_public_flag) ? 'shared' : 'private';
    var count = AIR2.Submission.SUBMCOUNT;
    var href = AIR2.HOMEURL + '/search/responses?q=inq_uuid%3D'+subm.Inquiry.inq_uuid;

    /* return the panel */
    var inqTitle = AIR2.Submission.SUBMDATA.radix.Inquiry;
    inqTitle = AIR2.Format.inquiryTitle(inqTitle, true);
    return new AIR2.UI.Panel({
        colspan: 2,
        rowspan: 3,
        style: 'min-height: 300px',
        title: inqTitle,
        cls: 'air2-submission-response',
        iconCls: 'air2-icon-list',
        storeData: AIR2.Submission.RESPDATA,
        url: AIR2.Submission.SUBMURL + '/responses.json',
        tools: ['->',
            '<span class="count-box air2-corners3"><a href="'+href+'">« '+count+' Submissions</a></span>'
        ],
        itemSelector: '.subm-response',
        tpl: new Ext.XTemplate(
            '<div class="subm-summary-inq air2-icon air2-icon-curve">' +
              '<div class="creator">' +
                'Query created by ' + creator + ' ' + org + ' on ' + dtim +
                '<span class="air2-corners3 sharing '+shared+'">'+shared+'</span>' +
              '</div>' +
            '</div>' +
            '<div class="subm-summary-resp air2-icon air2-icon-response">' +
              '<b>Submission from ' + src + ' on ' + submDate + '</b>' +
            '</div>' +
            // responses
            '<ol class="response-list"><tpl for=".">' +
              '<li class="subm-response">' +
                '<div class="question">' +
                  '<b>{[values.Question.ques_value]}</b>' +
                '</div>' +
                '<div class="response">' +
                  '{[this.formatResponse(values)]}' +
                '</div>' +
                '<div class="annotation">' +
                  '<span class="annot-count air2-corners3" ' +
                    'onclick="AIR2.Submission.Responses.showAnnotation(this, \'{sr_id}\')">' +
                    '{annot_count}' +
                  '</span>' +
                  '<div></div>' +
                '</div>' +
              '</li>' +
            '</tpl></ol>',
            {
                compiled: true,
                disableFormats: true,
                formatResponse: function(values) {
                    if (values.Question.ques_type == 'M') {
                        // multiple values
                        var str = '<ul class="multiple">';
                        var selects = values.sr_orig_value.split('|');
                        var choices = Ext.decode(values.Question.ques_choices);
                        for (var i=0; i<choices.length; i++) {
                            var val = choices[i].value;
                            var cls = (selects.indexOf(val) > -1) ? 'checked' : 'unchecked';
                            var def = choices[i].isdefault ? ' (default)' : '';
                            str += '<li class="'+cls+'">'+val+def+'</li>';
                        }
                        str += '</ul>';
                        return str;
                    }
                    else if (values.Question.ques_type == 'S') {
                        // single select
                        var sel = values.sr_orig_value;
                        str = '<ul class="single">';
                        choices = Ext.decode(values.Question.ques_choices);

                        // find start/end
                        var start = 0;
                        var end = choices.length;
                        if (choices.length > 10) {
                            // abbreviate choices
                            for (i=0; i<choices.length; i++) {
                                if (choices[i].value == sel) {
                                    start = Math.max(0, i-3);
                                    end = Math.min(start + 6, end);
                                    break;
                                }
                            }
                        }
                        for (i=start; i<end; i++) {
                            val = choices[i].value;
                            cls = (val == sel) ? 'checked' : 'unchecked';
                            def = choices[i].isdefault ? ' (default)' : '';
                            str += '<li class="'+cls+'">'+val+def+'</li>';
                        }
                        str += '</ul>';
                        return str;
                    }
                    else if (values.Question.ques_type == 'D') {
                        // date -- TODO: different than text at all?
                        return '<p class="text">' + values.sr_orig_value + '</p>';
                    }
                    else if (values.Question.ques_type == 'F') {
                        // file -- TODO: how the heck to handle this?
                        return '<p class="text">' + values.sr_orig_value + '</p>';
                    }
                    else {
                        // probably 'T' = plain text
                        return '<p class="text">' + values.sr_orig_value + '</p>';
                    }
                }
            }
        )
    });
}